package view.GUI.adminView.coreData.people.customer;

import model.data.interfaces.IWriteableToDB;
import model.data.tableModel.person.Customer;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.stage.Stage;
import enums.GUIText;
import enums.Status;
import view.GUI.adminView.coreData.people.EditBox;
import view.GUI.mainView.MainView;


public final class EditCustomer extends CustomerView{

	private EditBox editbox;
	
	public EditCustomer(MainView instance) {
		super(true, GUIText.EDITCUSTOMER, instance);
		editbox = new EditBox(valSup, GUIText.CUSTOMER, owner.getActiveCustomer());
		editbox.getComboBox().getSelectionModel().selectedItemProperty().addListener(new ChangeListener<IWriteableToDB>(){

			@Override
			public void changed(ObservableValue<? extends IWriteableToDB> arg0, IWriteableToDB arg1, IWriteableToDB newValue) {
				Customer c = (Customer) newValue;
				txtCustomerName.setText(c.getName());
				cmbPerson.getSelectionModel().select(c.getPerson());
			}
			
		});
		int columnCounter = 0;
		for(Node n: editbox.getNodes()){
			super.addNode(n, columnCounter++, 0);
			
		}
		try {
			start(new Stage());
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	protected boolean save() {
		Customer c = (Customer) editbox.getComboBox().getSelectionModel().getSelectedItem();
		if(editbox.isDeleteSelected()){
			c.setStatus(Status.INACTIVE);
			owner.deleteCustomer(c);
		} else{
			c.setName(txtCustomerName.getText());
			c.setPerson(cmbPerson.getSelectionModel().getSelectedItem());			
		}
		c.writeUpdateToDB();
		return true;
	}
}
